import os

import requests
from zhipuai import ZhipuAI

default_max_retry_count = 3
api_key="c532db69128fd53aa158f5da247effea.L5cEtl3JLNfIyMA5"

def sync_task_submit_call(input_prompt):
    client = ZhipuAI(api_key=api_key)  # 请填写您自己的APIKey

    task_upload_response = client.videos.generations(
        model="cogvideox",
        prompt=input_prompt
    )
    if task_upload_response.task_status == "FAIL":
        print('有提交失败任务')
        return 0, False
        #todo:重试
    if task_upload_response.id is None:
        print('有提交失败任务,无id返回')
        return 0, False
    return task_upload_response.id,True

def get_task_result(task_id, file_path, temp_file_name):
    client = ZhipuAI(api_key=api_key)  # 请填写您自己的APIKey
    dest_temp_file_name = file_path + os.sep + temp_file_name
    get_result_response = client.videos.retrieve_videos_result(
        id=task_id
    )
    while get_result_response.task_status != 'SUCCESS':
        get_result_response = client.videos.retrieve_videos_result(
            id=task_id
        )

        if get_result_response.task_status == "FAIL":
            return {"success": False, "value": None, "msg": "生成视频片段失败"}

    if not os.path.exists(file_path):
        os.makedirs(file_path)

    video_url = get_result_response.video_result[0].url
    cover_image_url = get_result_response.video_result[0].cover_image_url
    with open('./%s' % dest_temp_file_name, 'wb+') as f:
        f.write(requests.get(video_url).content)
    return True, cover_image_url, dest_temp_file_name
